var whois = require('whoisclient');
var request = require('request');

var whoisServer = 'http://whois.chinaz.com/';
var userAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)';

/**
 * 借助 whoisclient 查询
 */
var requestWhoisclient = function(domain) {
	if (is.empty(domain)) {
		console.log('[err] 域名不能为空');
		return 1;
	}
	whois.query(domain, function (data) {
			var whois = data;
			if (whois.indexOf('Creation Date: ') == -1) {
				// 域名未注册
				var stopTime = (new Date()).getTime();
				console.log('[suc]  ' + domain + '  ' + (stopTime - startTime) + ' ms  域名未注册');
			} else {
				// 域名已注册
				var createTime = whois.substr(whois.indexOf('Creation Date: ') + 15, 11);
				var stopTime = (new Date()).getTime();
				console.log('[suc]  ' + domain + '  ' + createTime + '  ' + (stopTime - startTime) + ' ms');
			}
	});
}

/**
 * 借助第三方网站实现 whois 查询
 * 万网：http://whois.www.net.cn/whois/domain/domainName
 * 站长之家：http://whois.chinaz.com/domainName
 */
var requestThirdparty = function (domain, server) {
	if (is.empty(domain)) {
		console.log('[err] 域名不能为空');
		return 1;
	}
	if (is.empty(server)) {
		server = whoisServer;
	}
	var startTime = (new Date()).getTime();
	var options = {
		'url' : server + domain,
		'headers' : {
			'User-Agent' : userAgent
		}
	};
	request(options, function (error, response, body) {
		if (!error && response.statusCode == 200) {
			//console.log(body); // Show the HTML
			var whois = body;
			if (whois.indexOf('创建时间') == -1) {
				// 域名未注册
				luckyDomain.push(domain);
				var stopTime = (new Date()).getTime();
				console.log('[suc]  ' + domain + '  ' + (stopTime - startTime) + ' ms  域名未注册');
			} else {
				// 域名已注册
				var createTime = whois.substring(whois.indexOf('<br/>创建时间：') + 10, whois.indexOf('<br/>过期时间'));
				var stopTime = (new Date()).getTime();
				console.log('[suc]  ' + domain + '  ' + createTime + '  ' + (stopTime - startTime) + ' ms');
			}
		} else {
			console.log('[err] 网络错误');
		}
	})
}

var requestWhois = function(domain) {
	return requestWhoisclient(domain);
}

module.exports = {
	'request':requestWhois
};
